package rcs34.android.AndroidRC;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.json.JSONException;
import org.json.JSONObject;

public class Commandline {
  private static final String abortMessage = "Operation failed";
  private Process process = null;
  
  synchronized public JSONObject processCommand(String[] cmd) {
    JSONObject data = new JSONObject();
    try {
      data.put("output", abortMessage);
      try {
        process = new ProcessBuilder().command(cmd).redirectErrorStream(true)
            .start();
      } catch (IOException e) {
        String message = e.getMessage() + "\n";
        Throwable cause = e.getCause();
        if (cause != null) {
          message += cause.getMessage() + "\n";
        }
        data.put("output", message);
        // e.printStackTrace();
        abort();
        return data;
      }
      try {
        BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(process.getInputStream()), 1024);
        StringBuffer response = new StringBuffer();
        while (true) {
          String line;
          line = bufferedReader.readLine();
          if (line == null) {
            break;
          } else {
            response.append(line);
            response.append("\n");
            if (response.length() > 1024 * 100) {
              response.append("******* Output truncated ******");
              response.append("\n");
              break;
            }
          }
        }
        data.put("output", response);
      } catch (IOException e) {
        data.put("output", e.getMessage());
        e.printStackTrace();
        return data;
      } finally {
        abort();
      }
    } catch (JSONException _e) {
      return data;
    }
    // System.out.println(new String(data));
    return data;
  }
  
  public void abort() {
    if (process != null) {
      process.destroy();
      process = null;
    }
  }
}
